package cn.gemframe.security.handler;

import cn.gemframe.constant.GemConstant;
import cn.gemframe.exception.status.GemErrorStatus;
import cn.gemframe.response.ResultData;
import cn.gemframe.utils.GemJsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class GemLoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		response.setContentType(GemConstant.MediaType.JSON_UTF_8);
		if(exception instanceof BadCredentialsException){
			response.getWriter().write(GemJsonUtils.objectToJson(ResultData.getResultWithCode(GemErrorStatus.PASSWORD_ERROR)));
		}else if(exception instanceof InternalAuthenticationServiceException){
			response.getWriter().write(GemJsonUtils.objectToJson(ResultData.getResultWithCode(GemErrorStatus.NOT_USER)));
		}else{
			log.error("---auth error:{}","GemLoginFailureHandler");
			response.getWriter().write(GemJsonUtils.objectToJson(ResultData.getResultWithCode(GemErrorStatus.AUTHENTICATION_FAILED)));
		}
	}
}
